import { defineStore } from 'pinia'
import { areaList } from '@vant/area-data'
import { LabelValueArray } from '@/framework/types/common-data'
import areaMapJson from './json/areaMap.json'

export const useAreaStore = defineStore('areaStore', {
  state: () => {
    const countryValueMap = new Map() as Map<string, string>
    const countryNameMap = new Map() as Map<string, string>
    const areaMap: any = areaMapJson
    return {
      areaList,
      countryNameMap,
      countryValueMap,
      countrySelectOption: [] as LabelValueArray,
      areaMap
    }
  },
  actions: {
    setCountrySelectOption(options: any) {
      options.forEach((country: any) => {
        this.countryNameMap.set(country.label, country.value)
        this.countryValueMap.set(country.value, country.label)
      })
      this.countrySelectOption = options || ([] as LabelValueArray)
    },
    initAreaMap() {
      const areaMap: any = {}
      new Map(Object.entries(areaList.province_list)).forEach((provinceName, provinceValue) => {
        const province = { value: provinceValue, label: provinceName, children: {} as any }
        areaMap[provinceName] = province
        new Map(Object.entries(areaList.city_list)).forEach((cityName, cityValue) => {
          const city = { value: cityValue, label: cityName, children: {} as any }
          if (cityValue.startsWith(provinceValue.slice(0, 2))) {
            province.children[cityName] = city
          }
          new Map(Object.entries(areaList.county_list)).forEach((countyName, countyValue) => {
            const county = { value: countyValue, label: countyName }
            if (countyValue.startsWith(city.value.slice(0, 4))) {
              city.children[countyName] = county
            }
          })
        })
      })
      return areaMap
    }
  },
  getters: {
    getAreaList: (state) => state.areaList,
    getAreaCode: (state) => {
      return (provinceName: any, cityName: any, countyName: any) => {
        const province = provinceName && state.areaMap[provinceName]
        const city = province && cityName && province.children[cityName]
        const county = city && countyName && city.children[countyName]
        return {
          province: province ? province.value : null,
          city: city ? city.value : null,
          county: county ? county.value : null
        }
      }
    },
    countrySelectOptions: (state) => state.countrySelectOption,
    getCountryValue: (state) => {
      return (name: string) => {
        return state.countryNameMap.get(name) || ''
      }
    },
    getCountryName: (state) => {
      return (value: string) => {
        return state.countryValueMap.get(value) || ''
      }
    }
  }
})
